package com.em.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.em.dao.DeviceInspectionMapper;
import com.em.dao.FeeMapper;
import com.em.entity.DeviceInspection;
import com.em.entity.Fee;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class FeeService {
    @Autowired
    private FeeMapper mapper;

    public List<Fee> select(String name) {
        QueryWrapper<Fee> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNoneBlank(name)) {
            queryWrapper.like("name", name);
        }
        return mapper.selectList(queryWrapper);
    }

    public int create(Fee entity) {
        long currentTime = System.currentTimeMillis();
        entity.setCreateTime(currentTime);
        entity.setUpdateTime(currentTime);
        return mapper.insert(entity);
    }

    public int update(Fee entity) {
        entity.setUpdateTime(System.currentTimeMillis());
        return mapper.updateById(entity);
    }

    public int delete(Integer id) {
        return mapper.deleteById(id);
    }

    public Fee selectById(Integer id) {
        return mapper.selectById(id);
    }

    public BigDecimal getTotalPaid() {
        List<Fee> select = select(null);
        return select.stream()
            .filter(it -> it.getStatus().equals("已支付"))
            .map(Fee::getAmount)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    public BigDecimal getTotalUnpaid() {
        List<Fee> select = select(null);
        return select.stream()
            .filter(it -> it.getStatus().equals("未支付"))
            .map(Fee::getAmount)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    public Map<String, BigDecimal> getFeeTypeStats() {
        List<Fee> select = select(null);
        return select.stream().collect(Collectors.groupingBy(
            Fee::getFeeType,
            Collectors.mapping(Fee::getAmount, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))
        ));
    }
}
